package com.uniview.utils;

import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * created by lux 06609
 * 常用的日期工具类
 */
public class CalendarUtils {

    /**
     * 获取当前日期字符串
     */
    public static String getDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 0);
        String date = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
        return date;
    }

    /**
     * 获取当前日期字符串
     */
    public static String getNDate() {
        Calendar cal = Calendar.getInstance();
        String date = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
        return date;
    }


    /**
     * 获取当前时间字符串
     */
    public static String getTime() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 0);
        String time = new SimpleDateFormat("HHmmss").format(cal.getTime());
        return time;
    }

    /**
     * 获取当前日期+时间
     */
    public static String getDateTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 0);
        String dateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(calendar.getTime());
        return dateTime;
    }

    /**
     * 获取当前日期时间
     *
     * @return Date 默认类型 yyyy-MM-dd HH:mm:ss
     */
    public static Date getNowDateTime() {
        return getNowDateTime("yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 获取当前日期时间
     *
     * @param format:格式化模板
     * @return Date 返回时间类型 yyyy-MM-dd HH:mm:ss
     */
    public static Date getNowDateTime(String format) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String dateString = formatter.format(currentTime);
        ParsePosition pos = new ParsePosition(0);
        Date currentTimeFormat = formatter.parse(dateString, pos);
        return currentTimeFormat;
    }

    /**
     * 将当前时间转换成ISO8601格式
     */
    public static String formatNowToISO8601() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        Date date = new Date();
        return formatter.format(date);
    }

    /**
     * 获取当前时间前5分钟
     *
     * @param offset:单位分钟，向前为-，向后为正
     * @return
     */
    public static String getOffsetBeforeNow(int offset) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, offset);// offset分钟之前的时间
        Date beforeD = beforeTime.getTime();
        String time = sdf.format(beforeD);
        return time;
    }


    /**
     * 获取前30天时间系列
     */
    public static List getThirtyDate() {
        List thirtyMap = new ArrayList();
        Calendar calc = Calendar.getInstance();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date kDate1 = calc.getTime();
        String thirtyDateStr1 = formatter.format(kDate1);
        thirtyMap.add(thirtyDateStr1);
        for (int k = 0; k < 29; k++) {
            calc.add(calc.DATE, -1);
            Date kDate = calc.getTime();
            String thirtyDateStr = formatter.format(kDate);
            thirtyMap.add(thirtyDateStr);
        }
        return thirtyMap;
    }


    /**
     * 获取当前短时间
     *
     * @return Date:返回当前日期
     */
    public static Date getNowDate() {
        return getNowDate("yyyy-MM-dd");
    }

    /**
     * 获取当前短时间
     *
     * @param format:日期格式
     * @return Date:返回当前日期
     */
    public static Date getNowDate(String format) {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        ParsePosition pos = new ParsePosition(0);
        Date currentTimeFormat = formatter.parse(dateString, pos);
        return currentTimeFormat;
    }

    /**
     * 日期转字符串
     */
    public static String dateToStr(Date date) {
        return dateToStr(date, "yyyy-MM-dd");
    }

    /**
     * 日期转字符串
     */
    public static String dateToStr(Date date, String format) {
        if ((null == date) || StringUtils.isBlank(format)) {
            return null;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(date);
    }

    /**
     * 字符串转日期
     *
     * @param dateStr ：传入的日期字符串
     */
    public static Date strToDate(String dateStr) throws Exception {
        return strToDate(dateStr, "yyyyMMddHHmmss");
    }

    /**
     * 字符串转日期
     *
     * @param dateStr ：传入的日期字符串
     * @param format  ：传入的日期字符串的格式
     */
    public static Date strToDate(String dateStr, String format) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = sdf.parse(dateStr);
        return date;
    }

    /**
     * 获取上月第一天和最后一天的日期
     *
     * @param: para=0:返回第一天日期
     * @param: para=-1:返回最后一天日期
     * @return: 第一天和最后一天的日期
     */
    public static Date getLastMonth(int para) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar lastDate = Calendar.getInstance();
        lastDate.add(Calendar.MONTH, -1);
        lastDate.set(Calendar.DATE, 1);
        lastDate.roll(Calendar.DATE, para);
        String str = sdf.format(lastDate.getTime());
        ParsePosition pos = new ParsePosition(0);
        Date currentTimeFormat = sdf.parse(str, pos);
        return currentTimeFormat;
    }

    /**
     * 获取上周一和周天的日期
     *
     * @param: para=1:代表周一
     * @param: para=7:代表周天
     * @return: 周一和周天的日期
     */
    public static Date getLastWeek(int para) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        int offset = para - dayOfWeek;
        calendar.add(Calendar.DATE, offset - 7);
        String lastEndDate = sdf.format(calendar.getTime());
        ParsePosition pos = new ParsePosition(0);
        Date currentTimeFormat = sdf.parse(lastEndDate, pos);
        return currentTimeFormat;
    }


    /**
     * 获取当前时间的上一年的最后一天和第一天日期
     *
     * @param
     * @return Date
     */
    public static Date getLastYear(int para) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 0);
        String date = new SimpleDateFormat("yyyy").format(cal.getTime());
        calendar.set(Calendar.YEAR, Integer.valueOf(date) - 1);
        calendar.roll(Calendar.DAY_OF_YEAR, para);
        Date lastYear = calendar.getTime();
        return lastYear;
    }


    public static List lastWeekEveryday() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar instance = Calendar.getInstance();
        // 调整到上周
        instance.add(Calendar.WEDNESDAY, -1);
        // 调整到上周1
        instance.set(Calendar.DAY_OF_WEEK, 2);
        List weekDayNum = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            weekDayNum.add(sdf.format(instance.getTime()));
            instance.add(Calendar.DAY_OF_WEEK, 1);
        }
        return weekDayNum;
    }


    /**
     * 根据给定的开始和结束日期，输出中间日期
     *
     * @param:
     * @param:
     * @return:
     */
    public static List<String> createDate(String beginTime, String endTime) throws Exception {
        DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd");
//        String beginTime="2019-04-27";
//        String endTime="2019-05-5";
        Calendar startDay = Calendar.getInstance();
        Calendar endDay = Calendar.getInstance();
        startDay.setTime(FORMATTER.parse(beginTime));
        endDay.setTime(FORMATTER.parse(endTime));
        Calendar currentPrintDay = startDay;
        List list = new ArrayList();
        while (true) {
            list.add(FORMATTER.format(currentPrintDay.getTime()));

            // 日期加一
            currentPrintDay.add(Calendar.DATE, 1);
            // 日期加一后判断是否达到终了日，达到则终止打印
            if (currentPrintDay.compareTo(endDay) == 0) {
                break;
            }
        }
        list.add(FORMATTER.format(endDay.getTime()));
        return list;

    }

    public static List<String> getTwelveMonth() {
        DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM");
        List<String> last12Months = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        //如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
        cal.set(Calendar.DAY_OF_MONTH, 1);
        for (int i = 0; i < 12; i++) {
            last12Months.add(FORMATTER.format(cal.getTime()));
            //last12Months.add(cal.get(Calendar.YEAR) + "-" + cal.get(Calendar.MONTH) + 1);
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月
        }
        for (String month : last12Months) {
            System.out.println(month);
        }
        return last12Months;
    }

    /**
     * description 校验8位字符串是否为正确的日期格式
     *
     * @param str 8位日期字符串
     * @return boolean
     */
    public static boolean isValidDate(String str) {
        boolean result = true;
        //判断字符串长度是否为8位
        if (str.length() == 8) {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            try {
                // 设置lenient为false.
                // 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
                format.setLenient(false);
                format.parse(str);
            } catch (ParseException e) {
                // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
                result = false;
            } catch (NullPointerException ex) {
                result = false;
            }
        } else {
            result = false;
        }
        return result;
    }

    public static boolean isValidTime(String str) {
        boolean result = true;
        //判断字符串长度是否为6位
        if (str.length() == 6) {
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            try {
                // 设置lenient为false.
                // 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
                format.setLenient(false);
                format.parse("20190808" + str);
            } catch (ParseException e) {
                // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
                result = false;
            } catch (NullPointerException ex) {
                result = false;
            }
        } else {
            result = false;
        }
        return result;
    }

    public static void main(String[] args) {
        /*try {
            String date = CalendarUtils.getDate();
            System.out.println("======" + date + "==========");
            String time = getTime();
            System.out.println("=====" + time + "===========");
            String dateTime = CalendarUtils.getDateTime();
            System.out.println("=====" + dateTime + "===========");
            System.out.println(strToDate(dateTime));
            System.out.println("===结束==");
            Date date1 = new Date();
            System.out.println(dateToStr(date1));
            Date date2 = getNowDateTime();
            System.out.println(date2);
            getTwelveMonth();

        } catch (Exception e) {
            e.printStackTrace();
        }*/
        String time = CalendarUtils.getOffsetBeforeNow(-5);
        System.out.println(time);
    }


}
